/**
 * DataParser.java
 * DataParser.java
 * 
 * Purpose              :
 * 
 * Optional info        : 
 *
 * @author              : Hoang Viet
 * 
 * @date                : Apr 6, 2012
 * 
 * @lastChangedRevision : 
 *
 * @lastChangedDate     :
 *
 */
package com.applink.sell_proof.api;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.util.Log;

import com.aplink.sell_proof.services.DataSync;
import com.applink.sell_proof.EMarketing;
import com.applink.sell_proof.Splash;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.database.table.AnalyticDBHelper;
import com.applink.sell_proof.database.table.ClaimDBHelper;
import com.applink.sell_proof.database.table.CountryDBHelper;
import com.applink.sell_proof.database.table.CustomerSupportHelper;
import com.applink.sell_proof.database.table.DistributorDBHelper;
import com.applink.sell_proof.database.table.PriceBookDBHelper;
import com.applink.sell_proof.database.table.ProductImageDBHelper;
import com.applink.sell_proof.database.table.ProductModelDBHelper;
import com.applink.sell_proof.database.table.ProjectDBHelper;
import com.applink.sell_proof.database.table.PromotionDBHelper;
import com.applink.sell_proof.database.table.QuestionDBHelper;
import com.applink.sell_proof.database.table.QuizDBHelper;
import com.applink.sell_proof.database.table.RewardClaimDBHelper;
import com.applink.sell_proof.database.table.RewardClaimDetailDBHelper;
import com.applink.sell_proof.database.table.RewardDBHelper;
import com.applink.sell_proof.database.table.RewardProjectDBHelper;
import com.applink.sell_proof.database.table.RewardProjectDetailDBHelper;
import com.applink.sell_proof.database.table.SPreferences;
import com.applink.sell_proof.database.table.TipDBHelper;
import com.applink.sell_proof.database.table.UserSettingDBHelper;
import com.applink.sell_proof.model.Claim;
import com.applink.sell_proof.model.ClaimImage;
import com.applink.sell_proof.model.Country;
import com.applink.sell_proof.model.CustomerSupport;
import com.applink.sell_proof.model.Distributor;
import com.applink.sell_proof.model.NewReward;
import com.applink.sell_proof.model.NewRewardClaim;
import com.applink.sell_proof.model.NewRewardClaimDetail;
import com.applink.sell_proof.model.NewRewardProject;
import com.applink.sell_proof.model.NewRewardProjectDetail;
import com.applink.sell_proof.model.PriceBook;
import com.applink.sell_proof.model.Product;
import com.applink.sell_proof.model.ProductImage;
import com.applink.sell_proof.model.Program;
import com.applink.sell_proof.model.ProgramReward;
import com.applink.sell_proof.model.Project;
import com.applink.sell_proof.model.Promotion;
import com.applink.sell_proof.model.Quiz;
import com.applink.sell_proof.model.QuizResultContent;
import com.applink.sell_proof.model.Redeem;
import com.applink.sell_proof.model.Sell;
import com.applink.sell_proof.model.Tier;
import com.applink.sell_proof.model.Tip;
import com.applink.sell_proof.model.Tip.Category;
import com.applink.sell_proof.model.UserSetting;
import com.applink.sell_proof.util.SimpleEntry;
import com.applink.sell_proof.util.Utility;

/**
 * @author Hoang Viet
 * 
 */

public class ParserDataHelper {
	private static final String TAG = "ParserDataHelper";
	private volatile static ParserDataHelper uniqueInstance;
	private boolean flagCheckPriceBook;
	private boolean flagCheckProduct;

	public static ParserDataHelper getInstance() {
		if (uniqueInstance == null) {
			synchronized (DataHelper.class) {
				if (uniqueInstance == null) {
					uniqueInstance = new ParserDataHelper();
				}
			}
		}
		return uniqueInstance;
	}

	/**
	 * Parse json string
	 * 
	 * @param data
	 * @param method
	 * @return All parser method return object ApiServiceResult
	 */

	public DataResult parse(String data, MethodParams methodparam) {
		if (data == null) {
			return null;
		}
		JSONArray jsonarray = null;
		try {
			// Log.e(TAG, data);
			// System.out.println(">>>data = " + data);
			if (data.trim().startsWith("{")) {
				data = String.format("[%s]", data.trim());
			}

			jsonarray = new JSONArray(data);
			switch (methodparam.getName()) {

			case getAllDistributor:
				return parseAllDistributor(jsonarray, methodparam);
			case updateClaim:
			case saveClaim:
			case createClaim:
			case deleteClaim:
				return parseCreateClaim(jsonarray, methodparam);
			case createDeal:
				return parseCreateDeal(jsonarray, methodparam);
			case updateOpportunity:
			case saveOpportunity:
			case createOpportunity:
				return parseCreateOpportunity(jsonarray, methodparam);
			case getAllDeal:
				return parseGetDeal(jsonarray, methodparam);
			case searchDeal:
				return parseSearchDeal(jsonarray, methodparam);
			case getAllCountry:
				return parseAllCountry(jsonarray, methodparam);
			case getTips:
				return parseGetTips(jsonarray, methodparam);
			case searchTip:
				return parseSearchTips(jsonarray, methodparam);
			case getTipDetail:
				return parseTipDetail(jsonarray, methodparam);
			case updateDeal:
			case replyQuiz:
				return parseResult(jsonarray, methodparam);
			case getAllQuiz:
				return parseAllQuiz(jsonarray, methodparam);
			case searchQuiz:
				return searchQuiz(jsonarray, methodparam);
			case getQuizDetail:
				return parseQuizDetail(jsonarray, methodparam);
			case getCustomerProduct:
				return parseCustomerSupport(jsonarray, methodparam);
			case getCustomerInfor:
				return parseUserProfile(jsonarray, methodparam);
			case getAllCampaign:
				return parseListCampain(jsonarray, methodparam);
			case getAllProgramByCompaign:
				return parseListProgram(jsonarray, methodparam);
			case getEarnedRewardByCampaign:
			case getEarnedStatement:
				return parseEarnedRewardByCampaign(jsonarray, methodparam);
			case getProgramDetail:
				return parseListTier(jsonarray, methodparam);
			case getPreviousRedeem:
				return parsePreviousRedeem(jsonarray, methodparam);
			case saveRedeem:
				return parseSaveRedeem(jsonarray, methodparam);
			case getRedeemDetail:
				return parseRedeemDetail(jsonarray, methodparam);
			case changePass:
				return parseChangePassword(jsonarray, methodparam);
			case resetPass:
				return parseResetPassword(jsonarray, methodparam);
			case invitationCode:
				return parseInvitation(jsonarray, methodparam);
			case Login:
				return parseLogin(jsonarray, methodparam);
			case getDealDetail:
				return parseDealDetail(jsonarray, methodparam);
			case getPresetResultQuiz:
				return parseQuizPresetAnswer(jsonarray, methodparam);
			case getQuizResult:
				return parseQuizResult(jsonarray, methodparam);
			case searchProductModel:
				return parseSearchProductModel(jsonarray, methodparam);
			case getOpportunityByStatus:
				return parseGetOpportunityByStatus(jsonarray, methodparam);
			case getOpportunityDetail:
				return parseDetailOpportunity(jsonarray, methodparam);
			case searchOpportunity:
				return parseSearchOpportunity(jsonarray, methodparam);
			case deleteOpportunity:
				return parseDeleteOpportunity(jsonarray, methodparam);
			case getClaimByStatus:
				return parseGetClaimByStatus(jsonarray, methodparam);
			case getClaimDetail:
				return parseDetailClaim(jsonarray, methodparam);
			case getPriceBook:
				return parsePriceBook(jsonarray, methodparam);
			case getPromotion:
				return parsePromotion(jsonarray, methodparam);
			case getProductImage:
				return parseProductImage(jsonarray, methodparam);
			case getReward:
				return parseReward(jsonarray, methodparam);
			case getRewardProject:
				return parseRewardProject(jsonarray, methodparam);
			case getRewardClaim:
				return parseRewardClaim(jsonarray, methodparam);
			case getRewardProjectDetail:
				return parseRewardProjectDetail(jsonarray, methodparam);
			case getRewardClaimDetail:
				return parseRewardClaimDetail(jsonarray, methodparam);
			case updateUserActivity:
				return parseLogDate(jsonarray, methodparam);
			default:
				break;
			}
		} catch (JSONException e) {
			Log.e(TAG, "parse error " + e.toString());
			if (jsonarray != null) {
				try {
					JSONObject loginError = jsonarray.getJSONObject(0);
					if (loginError.getString("Error").equals(
							"Did not login yet")) {
						EMarketing.getInstance().setLogin(false);
						Intent intent = new Intent(EMarketing.getInstance()
								.getApplicationContext(), Splash.class);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						EMarketing.getInstance().getApplicationContext()
								.startActivity(intent);
					}
				} catch (JSONException e1) {
					DataResult result = new DataResult();
					result.setErrorCode(ErrorCode.DID_NOT_LOGIN);
					return result;
				}
			}
			DataResult result = new DataResult();
			result.setErrorCode(ErrorCode.UNKNOWN_ERROR);
			return result;
		}
		return null;
	}

	private DataResult parseAllDistributor(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		Distributor distributor = new Distributor();
		distributor.setId(0);
		distributor.setName("Select");
		DistributorDBHelper.createDistributor(distributor);
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonDistributor = (JSONObject) jsonarray.get(i);
			distributor.setId(jsonDistributor.getLong("DistributorID"));
			distributor.setName(jsonDistributor.getString("DistributorName"));
			DistributorDBHelper.createDistributor(distributor);
		}
		return result;
	}

	private DataResult parseAllCountry(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonDistributor = (JSONObject) jsonarray.get(i);
			Country country = new Country();
			country.setCode(jsonDistributor.getInt("CountryID"));
			country.setName(jsonDistributor.getString("Country"));
			country.setPostalCode(jsonDistributor.getString("CountryPhoneCode"));

			CountryDBHelper.createCountry(country);
		}
		return result;
	}

	private DataResult parseCustomerSupport(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();

		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonDistributor = (JSONObject) jsonarray.get(i);
			CustomerSupport cusEntity = new CustomerSupport();
			cusEntity.setClient_sale_email(jsonDistributor
					.getString("ClientSaleSupportEmail"));
			cusEntity.setClient_sale_hotline(jsonDistributor
					.getString("ClientSaleSupportHotline"));
			cusEntity.setClient_tech_email(jsonDistributor
					.getString("ClientTechSupportEmail"));
			cusEntity.setClient_tech_hotline(jsonDistributor
					.getString("ClientTechSupportHotline"));
			cusEntity
					.setProgramemail(jsonDistributor.getString("ProgramEmail"));
			cusEntity.setProgramhotline(jsonDistributor
					.getString("ProgramHotline"));

			CustomerSupportHelper.InsertCustomerSupport(cusEntity);
		}

		return result;
	}

	private DataResult parseUserProfile(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();

		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonUserSetting = (JSONObject) jsonarray.get(i);
			UserSetting userSetting = new UserSetting();

			userSetting.setUserId(i + 1);

			String webLogin = jsonUserSetting.getString("WebLogin");
			if (webLogin.equals("null")) {
				webLogin = " ";
			}
			userSetting.setWebLogin(webLogin);

			String salutation = jsonUserSetting.getString("Salutation");
			if (salutation.equals("null")) {
				salutation = " ";
			}
			userSetting.setSalutation(salutation);

			String firstName = jsonUserSetting.getString("FirstName");
			if (firstName.equals("null")) {
				firstName = " ";
			}
			userSetting.setFirstName(firstName);

			String lastName = jsonUserSetting.getString("LastName");
			if (lastName.equals("null")) {
				lastName = " ";
			}
			userSetting.setLastName(lastName);

			String Mobile1 = jsonUserSetting.getString("Mobile1");
			if (Mobile1.equals("null")) {
				Mobile1 = " ";
			}
			userSetting.setMobile1(Mobile1);

			String Email1 = jsonUserSetting.getString("Email1");
			if (Email1.equals("null")) {
				Email1 = " ";
			}
			userSetting.setEmail1(Email1);

			String JobTitle = jsonUserSetting.getString("JobTitle");
			if (JobTitle.equals("null")) {
				JobTitle = " ";
			}
			userSetting.setJobTitle(JobTitle);

			String PartnerCompName = jsonUserSetting
					.getString("PartnerCompName");
			if (PartnerCompName.equals("null")) {
				PartnerCompName = " ";
			}
			userSetting.setPartnerCompName(PartnerCompName);

			String Country = jsonUserSetting.getString("Country");
			if (Country.equals("null")) {
				Country = " ";
			}
			userSetting.setCountry(Country);

			String PartnerCompAddress1 = jsonUserSetting
					.getString("PartnerCompAddress1");
			if (PartnerCompAddress1.equals("null")) {
				PartnerCompAddress1 = " ";
			}
			userSetting.setPartnerCompAddress1(PartnerCompAddress1);

			String PartnerCompAddress2 = jsonUserSetting
					.getString("PartnerCompAddress2");
			if (PartnerCompAddress2.equals("null")) {
				PartnerCompAddress2 = " ";
			}
			userSetting.setPartnerCompAddress2(PartnerCompAddress2);

			String PartnerCompAddress3 = jsonUserSetting
					.getString("PartnerCompAddress3");
			if (PartnerCompAddress3.equals("null")) {
				PartnerCompAddress3 = " ";
			}
			userSetting.setPartnerCompAddress3(PartnerCompAddress3);

			String PartnerCompPostCode = jsonUserSetting
					.getString("PartnerCompPostCode");
			if (PartnerCompPostCode.equals("null")) {
				PartnerCompPostCode = " ";
			}
			userSetting.setPartnerCompPostCode(PartnerCompPostCode);

			String PartnerCompOfficeNo1 = jsonUserSetting
					.getString("PartnerCompOfficeNo1");
			if (PartnerCompOfficeNo1.equals("null")) {
				PartnerCompOfficeNo1 = " ";
			}
			userSetting.setPartnerCompOfficeNo1(PartnerCompOfficeNo1);

			String PartnerCompFax = jsonUserSetting.getString("PartnerCompFax");
			if (PartnerCompFax.equals("null")) {
				PartnerCompFax = " ";
			}
			userSetting.setPartnerCompFax(PartnerCompFax);

			UserSettingDBHelper.createUserSetting(userSetting);
			// UserProfile entity = new UserProfile();

			// entity.setCountryName(jsonDistributor
			// .getString(Constant.USPF_COUNTRY));
			// entity.setCountryCode(jsonDistributor
			// .getInt(Constant.USPF_COUNTRYCODE));
			// entity.setDeliAddBuildName(jsonDistributor
			// .getString(Constant.DELIVERY_BUILDNAME));
			// entity.setDeliAddCountryCode(jsonDistributor
			// .getInt(Constant.DELIVERY_COUNTRYCODE));
			// entity.setDeliAddCountryName(jsonDistributor
			// .getString(Constant.DELIVERY_COUNTRY));
			// entity.setDeliAddPostalCode(jsonDistributor
			// .getString(Constant.DELIVERY_POSTALCODE));
			// entity.setDeliAddStreetName(jsonDistributor
			// .getString(Constant.DELIVERY_STREETNAME));
			// entity.setDeliAddUnit(jsonDistributor
			// .getString(Constant.DELIVERY_UNIT));
			//
			// entity.setDesignation(jsonDistributor
			// .getString(Constant.USPF_DESIGNATION));
			// entity.setEmail(jsonDistributor.getString(Constant.USPF_EMAIL));
			// entity.setFirstname(jsonDistributor
			// .getString(Constant.USPF_FIRSTNAME));
			// entity.setLastname(jsonDistributor
			// .getString(Constant.USPF_LASTNAME));
			// entity.setMobileNo(jsonDistributor.getString(Constant.USPF_MOBILE));
			// entity.setOffAddBuildName(jsonDistributor
			// .getString(Constant.OFFICE_BUILDNAME));
			//
			// entity.setOffAddCountryCode(jsonDistributor
			// .getInt(Constant.OFFICE_COUNTRYCODE));
			// entity.setOffAddCountryName(jsonDistributor
			// .getString(Constant.OFFICE_COUNTRY));
			// entity.setOffAddPostalCode(jsonDistributor
			// .getString(Constant.OFFICE_POSTALCODE));
			// entity.setOffAddStreetName(jsonDistributor
			// .getString(Constant.OFFICE_STREETNAME));
			// entity.setOffAddUnit(jsonDistributor
			// .getString(Constant.OFFICE_UNIT));
			// entity.setOrangeName(jsonDistributor
			// .getString(Constant.USPF_ORGANNAME));
			// entity.setSalutation(jsonDistributor
			// .getString(Constant.USPF_SALUTATION));
			// entity.setUserID(jsonDistributor.getString(Constant.USPF_USERID));
			//
			// CustomerSupportHelper.InsertUserPorfileToSharePref(entity);
		}

		return result;
	}

	private DataResult parseCreateDeal(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonDeal;
		jsonDeal = (JSONObject) jsonarray.get(0);
		if (jsonDeal != null) {
			Sell deal = new Sell();
			result.setData(deal);
		}
		return result;
	}

	private DataResult parseGetDeal(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		return result;
	}

	private DataResult parseSearchDeal(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		List<Sell> deals = new ArrayList<Sell>();
		result.setData(deals);
		return result;
	}

	private DataResult parseResult(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonDeal;
		jsonDeal = (JSONObject) jsonarray.get(0);
		if (jsonDeal != null) {
			jsonDeal.getString("Result");
		}

		return result;
	}

	private DataResult parseGetTips(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {

		if (Utility.countTip == 0) {
			Utility.countTip = jsonarray.length();
			Utility.checkTip = true;
		} else if (Utility.countTip < jsonarray.length()) {
			Utility.checkTip = true;
		} else {
			Utility.checkTip = false;
		}
		DataResult result = new DataResult();
		Tip.Category category = (Category) methodparams.getInputData();
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonDistributor = (JSONObject) jsonarray.get(i);
			Tip tip = new Tip();
			tip.setId(jsonDistributor.getInt("TipID"));
			// tip.setSave(jsonDistributor.getBoolean("isSaved"));
			tip.setSave(jsonDistributor.getString("isSaved").equals("True"));
			tip.setName(jsonDistributor.getString("TipName"));
			tip.setParagraph(jsonDistributor.getString("TipParagraph"));
			tip.setCategory(category);
			String date = jsonDistributor.getString("CreatedDate");
			try {
				Date createDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.TAIWAN).parse(date);
				tip.setDate(createDate.getTime());
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			}

			TipDBHelper.createTip(tip);
		}
		return result;
	}

	private DataResult parseSearchTips(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		List<Tip> tips = new ArrayList<Tip>();
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonSearchTip = (JSONObject) jsonarray.get(i);
			Tip tip = new Tip();
			tip.setId(jsonSearchTip.getInt("TipID"));
			tip.setName(jsonSearchTip.getString("TipName"));
			tip.setParagraph(jsonSearchTip.getString("TipParagraph"));
			Tip.Category category = Tip.Category.getCategory(jsonSearchTip
					.getInt("TipCategoryID"));
			tip.setCategory(category);
			String date = jsonSearchTip.getString("CreatedDate");
			try {
				Date createDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.TAIWAN).parse(date);
				tip.setDate(createDate.getTime());
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			}
			tips.add(tip);
			TipDBHelper.createTip(tip);
		}
		result.setData(tips);
		return result;
	}

	private DataResult parseTipDetail(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonTip = (JSONObject) jsonarray.get(0);
		if (jsonTip != null) {

			Tip tip = new Tip();
			tip.setId(jsonTip.getLong("TipID"));

			String htmlTip = String.format("<br/><p>%s</p><br/>",
					jsonTip.getString("TipFullText"));

			tip.setFulltext(htmlTip);

			// store the tip to the Tip local DB
			TipDBHelper.updateTip(tip);
		}
		return result;
	}

	// APLink --- anh Thiện
	private DataResult parseAllQuiz(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		if (Utility.countQuiz == 0) {
			Utility.countQuiz = jsonarray.length();
			Utility.checkQuiz = true;
		} else if (Utility.countQuiz < jsonarray.length()) {
			Utility.checkQuiz = true;
		} else {
			Utility.checkQuiz = false;
		}
		Quiz.Category category = (com.applink.sell_proof.model.Quiz.Category) methodparams
				.getInputData();
		DataResult result = new DataResult();
		for (int i = 0; i < jsonarray.length(); i++) {

			int countDate = 0;
			JSONObject jsonQuiz = (JSONObject) jsonarray.get(i);
			Quiz quiz = new Quiz();
			quiz.setId(jsonQuiz.getLong("QuizCampaignID"));
			quiz.setSubmitted(jsonQuiz.getString("QuizStatus").equals(
					"Submitted"));
			quiz.setName(jsonQuiz.getString("QuizCampaignName"));
			quiz.setDescription(jsonQuiz.getString("Description"));
			quiz.setCategory(category);
			String closeDate = jsonQuiz.getString("CloseDate");
			// for(int x = 0;x< closeDate.trim().length();x++){
			// String temp=closeDate.charAt(x)+"";
			// if(temp.equals(" "))
			// {
			// countDate = x;
			// break;
			// }
			// //if(closeDate.charAt(x))
			// }
			// Log.d("CloseDate","web service :"+closeDate);
			// String lastDate = closeDate.substring(0, countDate);
			try {
				Date date = new SimpleDateFormat("MM/dd/yyyy", Locale.TAIWAN)
						.parse(closeDate);
				// Log.d("CloseDate","convert date:"+date.toString());
				quiz.setEndDate(date.getTime());
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			}

			QuizDBHelper.createQuiz(quiz);
		}
		return result;
	}

	// private DataResult parseAllQuiz(JSONArray jsonarray,
	// MethodParams methodparams) throws JSONException {
	// Quiz.Category category = (com.applink.sell_proof.model.Quiz.Category)
	// methodparams
	// .getInputData();
	// DataResult result = new DataResult();
	// for (int i = 0; i < jsonarray.length(); i++) {
	// JSONObject jsonQuiz = (JSONObject) jsonarray.get(i);
	// Quiz quiz = new Quiz();
	// quiz.setId(jsonQuiz.getLong("QuizCampaignID"));
	// quiz.setSubmitted(jsonQuiz.getString("QuizStatus").equals(
	// "Submitted"));
	// quiz.setName(jsonQuiz.getString("QuizCampaignName"));
	// quiz.setDescription(jsonQuiz.getString("Description"));
	// quiz.setCategory(category);
	// String closeDate = jsonQuiz.getString("CloseDate");
	// try {
	// Date date = new SimpleDateFormat("dd/MM/yyyy", Locale.TAIWAN)
	// .parse(closeDate);
	// // Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
	// // .parse(closeDate);
	// quiz.setEndDate(date.getTime());
	// } catch (ParseException e) {
	// Log.e(TAG, e.toString());
	// }
	//
	// QuizDBHelper.createQuiz(quiz);
	// }
	// return result;
	// }

	private DataResult searchQuiz(JSONArray jsonarray, MethodParams methodparams)
			throws JSONException {
		DataResult result = new DataResult();
		List<Quiz> quizzes = new ArrayList<Quiz>();
		for (int i = 0; i < jsonarray.length(); i++) {
			JSONObject jsonQuiz = (JSONObject) jsonarray.get(i);
			Quiz quiz = new Quiz();
			quiz.setId(jsonQuiz.getLong("QuizCampaignID"));
			quiz.setName(jsonQuiz.getString("QuizCampaignName"));
			quiz.setDescription(jsonQuiz.getString("Description"));
			Quiz.Category category = Quiz.Category.getCategory(jsonQuiz
					.getInt("QuizCategoryID"));
			quiz.setCategory(category);
			String closeDate = jsonQuiz.getString("CloseDate");
			try {
				Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
						.parse(closeDate);
				quiz.setEndDate(date.getTime());
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			}
			quizzes.add(quiz);
			QuizDBHelper.createQuiz(quiz);
		}
		result.setData(quizzes);
		return result;
	}

	private DataResult parseQuizDetail(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		long quizId = (Long) methodParams.getInputData();
		DataResult result = new DataResult();
		List<Long> questionIds = new ArrayList<Long>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject question = (JSONObject) jsonArray.get(i);
			long questionID = question.getLong("QuestionID");
			questionIds.add(questionID);
			String content = question.getString("Question");
			JSONArray answers = question.getJSONArray("AnswerList");
			for (int j = 0; j < answers.length(); j++) {
				JSONObject answer = (JSONObject) answers.get(j);
				long answerId = answer.getLong("QuizReplyDetailID");
				String answerContent = answer.getString("AnswerContent");
				String answerType = answer.getString("AnswerType");
				String userReply = answer.getString("UserReply");
				QuestionDBHelper.createQuestion(quizId, questionID, answerId,
						content, userReply, answerContent, answerType);
			}
		}
		result.setData(questionIds);
		return result;
	}

	// private DataResult parseQuizDetail(JSONArray jsonArray,
	// MethodParams methodParams) throws JSONException {
	// long quizId = (Long) methodParams.getInputData();
	// DataResult result = new DataResult();
	// List<Integer> questionIds = new ArrayList<Integer>();
	// for (int i = 0; i < jsonArray.length(); i++) {
	// JSONObject question = (JSONObject) jsonArray.get(i);
	// int questionID = question.getInt("QuestionID");
	// questionIds.add(questionID);
	// String content = question.getString("Question");
	// JSONArray answers = question.getJSONArray("PresetAnswer");
	// for (int j = 0; j < answers.length(); j++) {
	// JSONObject answer = (JSONObject) answers.get(j);
	//
	// PresetAnswer presetAnswer = new PresetAnswer();
	//
	// presetAnswer.setOptionID(answer.getInt("OptionID"));
	// presetAnswer.setOptionName(answer.getString("OptionName"));
	// //presetAnswer.getOptionID().add(presetAnswer);
	//
	// }
	// }
	// result.setData(questionIds);
	// return result;
	// }

	private DataResult parseListCampain(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		List<Entry<Long, String>> campaigns = new ArrayList<Map.Entry<Long, String>>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject campaign = (JSONObject) jsonArray.get(i);
			long campainId = campaign.getLong("RewardTypeID");
			String campainName = campaign.getString("RewardTypeName");
			Entry<Long, String> entry = new SimpleEntry<Long, String>(
					campainId, campainName);
			campaigns.add(entry);
			result.setData(campaigns);
		}
		return result;
	}

	private DataResult parseListProgram(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		String campaignName = (String) methodParams.getInputData();
		List<Program> programs = new ArrayList<Program>();
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				JSONObject programJson = (JSONObject) jsonArray.get(i);
				Program program = new Program();
				program.setCategory(campaignName);
				program.setId(programJson.getLong("CampaignID"));
				program.setName(programJson.getString("CampaignName"));
				program.setDescription(programJson.getString("Description"));
				program.setPoint(programJson.getInt("ArchievedPoints"));
				Date startDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.TAIWAN)
						.parse(programJson.getString("StartDate"));
				Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
						.parse(programJson.getString("EndDate"));
				program.setStartdate(startDate.getTime());
				program.setEnddate(endDate.getTime());
				programs.add(program);
			} catch (ParseException e) {
				Log.e(TAG, e.toString());
			}
			result.setData(programs);
		}
		return result;
	}

	private DataResult parseEarnedRewardByCampaign(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		Map<String, Integer> summary = new HashMap<String, Integer>();
		JSONObject objectSummary = (JSONObject) jsonArray.get(0);
		summary.put("Total", objectSummary.getInt("Total"));
		summary.put("Redeemed", objectSummary.getInt("Redeemed"));
		summary.put("Balance", objectSummary.getInt("Balance"));
		result.setData(summary);
		return result;
	}

	private DataResult parseListTier(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		List<Tier> tiers = new ArrayList<Tier>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject programJson = (JSONObject) jsonArray.get(i);
			Tier tier = new Tier();
			tier.setId(programJson.getLong("TierLevelID"));
			tier.setName(programJson.getString("TierLevelName"));
			tier.setDescription(programJson.getString("TierDescription"));
			tier.setMaxEligible(programJson.getInt("MaxPoint"));
			tier.setMinEligible(programJson.getInt("MinPoint"));
			tier.setProduct(programJson.getString("ProductName"));
			tier.setRedeemable(programJson.getBoolean("Redemption"));
			tier.setAchivePoint(programJson.getInt("ArchievedPoints"));
			try {
				Date startDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.TAIWAN).parse(programJson
						.getString("RedemStartDate"));
				Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
						.parse(programJson.getString("RedemEndDate"));
				tier.setEndDate(endDate.getTime());
				tier.setStartDate(startDate.getTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			tiers.add(tier);
			result.setData(tiers);
		}
		return result;
	}

	private DataResult parsePreviousRedeem(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		List<Redeem> redeemSubmitted = new ArrayList<Redeem>();
		List<Redeem> redeemPrevious = new ArrayList<Redeem>();
		for (int i = 0; i < jsonArray.length(); i++) {
			try {
				JSONObject programJson = (JSONObject) jsonArray.get(i);
				Redeem redeem = new Redeem();
				redeem.setId(programJson.getLong("RedeemDeliveryID"));
				redeem.setTierId(programJson.getLong("TierLevelID"));
				redeem.setPoint(programJson.getInt("RedeemedPoints"));
				redeem.setProduct(programJson.getString("ProductName"));
				redeem.setProgramName(programJson.getString("CampaignName"));
				redeem.setCampaignName(programJson.getString("RewardTypeName"));
				redeem.setStatus(programJson.getString("ApprovalStatus"));
				Date redeemDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.TAIWAN).parse(programJson
						.getString("RedeempDate"));
				redeem.setDate(redeemDate.getTime());
				if (redeem.getStatus().equals("New")) {
					redeemSubmitted.add(redeem);
				} else {
					redeemPrevious.add(redeem);
				}
			} catch (ParseException e) {
				result.setErrorCode(ErrorCode.UNKNOWN_ERROR);
				return result;
			}

			Map<Integer, List<Redeem>> map = new HashMap<Integer, List<Redeem>>();

			map.put(0, redeemSubmitted);
			map.put(1, redeemPrevious);
			result.setData(map);
		}
		return result;
	}

	private DataResult parseRedeemDetail(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		try {
			JSONObject redeemJson = (JSONObject) jsonArray.get(0);
			Redeem redeem = new Redeem();
			redeem.setMinEligible(redeemJson.getInt("MinPoint"));
			redeem.setMaxEligible(redeemJson.getInt("MaxPoint"));
			redeem.setProduct(redeemJson.getString("ProductName"));
			redeem.setFirstName(redeemJson.getString("DeliveryFirstName"));
			redeem.setLastName(redeemJson.getString("DeliveryLastName"));
			redeem.setEmail(redeemJson.getString("DeliveryEmail1"));
			redeem.setMobile(redeemJson.getString("DeliveryMobile1"));
			redeem.setStreet(redeemJson.getString("StreetnameDelivery"));
			redeem.setPostalCode(redeemJson.getString("PostalCodeDelivery"));
			redeem.setCountryName(redeemJson.getString("Country"));

			redeem.setBuilding(redeemJson.getString("BuildingnameDelivery"));
			redeem.setUnit(redeemJson.getString("UnitnameDelivery"));
			Date startDate = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
					.parse(redeemJson.getString("StartDate"));
			Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
					.parse(redeemJson.getString("EndDate"));
			redeem.setStartdate(startDate.getTime());
			redeem.setEnddate(endDate.getTime());
			result.setData(redeem);
		} catch (ParseException e) {
		}
		return result;
	}

	private DataResult parseSaveRedeem(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonResult;
		jsonResult = (JSONObject) jsonarray.get(0);
		if (jsonResult != null) {
			jsonResult.getString("Redeem");
		}

		return result;
	}

	private DataResult parseInvitation(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonResult;
		try {
			jsonResult = (JSONObject) jsonarray.get(0);
			if (jsonResult != null && jsonResult.getString("Result") != null) {
				int code = Integer.parseInt(jsonResult.getString("Result"));
				System.out.println(">>>>>>>>>>>>> Login = " + code);
				result.setData(code); // 0 false 1 true 2 set new password
				// if (code == 0) {
				// //invalid
				//
				// } else if (code == 1) {
				// //valid
				// }else{
				// //active
				//
				// }
			} else {
				result.setData(0);
			}

		} catch (JSONException e) {
			result.setErrorCode(ErrorCode.UNKNOWN_ERROR);
		}
		return result;
	}

	private DataResult parseLogin(JSONArray jsonarray, MethodParams methodparams) {
		DataResult result = new DataResult();
		JSONObject jsonResult;
		try {
			jsonResult = (JSONObject) jsonarray.get(0);
			if (jsonResult != null) {
				try {
					Utility.checkExpireDay(jsonResult
							.getString("TokenExpiryDate"));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int code = jsonResult.getInt("Result");
				result.setData(code); // 0 false 1 true 2 set new password
				if (code == 1) {
					String token = jsonResult.getString("Token");
					EMarketing.getInstance().setAccountToken(token);
					EMarketing.getInstance().setAccountId(
							jsonResult.getString("ContactID"));
					EMarketing.getInstance().setLogin(true);
					if (EMarketing.getInstance().getContactID() != null
							&& !(EMarketing.getInstance().getContactID()
									.equals(jsonResult.getString("ContactID")))) {
						Constant.CHECK_ACCOUNT = true;
					}
					EMarketing.getInstance().setContactID(
							jsonResult.getString("ContactID"));
					EMarketing.getInstance().setLogin(true);
				} else if (code == 2) {
					String token = jsonResult.getString("Token");
					EMarketing.getInstance().setAccountToken(token);
				}
			}

		} catch (JSONException e) {
			result.setErrorCode(ErrorCode.UNKNOWN_ERROR);
		}
		return result;
	}

	// ----Get data Log-------------
	private DataResult parseLogDate(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonResult;
		try {
			jsonResult = (JSONObject) jsonarray.get(0);
			if (jsonResult != null && jsonResult.getString("Result") != null) {
				int code = Integer.parseInt(jsonResult.getString("Result"));
				// result.setData(code); // 0 false 1 true 2 set new password
				System.out.println("<<<<<< Log Code = " + code);
				if (code == 0) {
					AnalyticDBHelper.emptyTable();
				}
			}

		} catch (JSONException e) {
			result.setErrorCode(ErrorCode.UNKNOWN_ERROR);
		}
		return result;

	}

	private DataResult parseChangePassword(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonResult;
		jsonResult = (JSONObject) jsonarray.get(0);
		if (jsonResult != null) {
			int code = jsonResult.getInt("Result");
			result.setData(code);

		}

		return result;
	}

	private DataResult parseResetPassword(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		JSONObject jsonResult;
		jsonResult = (JSONObject) jsonarray.get(0);
		if (jsonResult != null) {
			String code = jsonResult.getString("Result");
			result.setData(code);
		}

		return result;
	}

	private DataResult parseDealDetail(JSONArray jsonarray,
			MethodParams methodparams) throws JSONException {
		DataResult result = new DataResult();
		return result;
	}

	private DataResult parseQuizPresetAnswer(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		long quizId = (Long) methodParams.getInputData();
		DataResult result = new DataResult();
		List<Long> questionIds = new ArrayList<Long>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject question = (JSONObject) jsonArray.get(i);
			long questionID = question.getLong("QuestionID");
			questionIds.add(questionID);
			JSONArray answers = question.getJSONArray("AnswerList");
			for (int j = 0; j < answers.length(); j++) {
				JSONObject answer = (JSONObject) answers.get(j);
				long answerId = answer.getLong("QuizReplyDetailID");
				String correctAnswer = answer.getString("CorrectAnswer");
				QuestionDBHelper.updateAnswerResult(quizId, questionID,
						answerId, correctAnswer);
			}
		}
		result.setData(questionIds);
		return result;
	}

	private DataResult parseQuizResult(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		QuizResultContent quizResult = new QuizResultContent();
		JSONObject jsonObject = (JSONObject) jsonArray.get(0);
		quizResult.setPoint(jsonObject.getInt("Points"));
		quizResult.setWinner(jsonObject.getBoolean("IsWinner"));
		if (quizResult.isWinner()) {
			quizResult.setRewardProduct(jsonObject.getString("ProductName"));
			try {
				Date startDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.TAIWAN).parse(jsonObject
						.getString("RedemStartDate"));
				Date endDate = new SimpleDateFormat("yyyy-MM-dd", Locale.TAIWAN)
						.parse(jsonObject.getString("RedemEndDate"));
				quizResult.setStartRedeem(startDate.getTime());
				quizResult.setEndRedeem(endDate.getTime());
			} catch (ParseException e) {
				// Log.e(TAG, "format time error");
			}
		}
		result.setData(quizResult);
		return result;
	}

	private DataResult parseSearchProductModel(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();

		List<Product> productModels = new ArrayList<Product>();

		List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();

		for (int i = 0; i < jsonArray.length(); i++) {
			Product productModel = new Product();
			HashMap<String, String> record = new HashMap<String, String>();

			JSONObject jsonModel = jsonArray.getJSONObject(i);

			record.put(ProductModelDBHelper.ID,
					jsonModel.getString("ProductID"));
			record.put(ProductModelDBHelper.MODEL_CATEGORY,
					jsonModel.getString("ProductCategoryName"));
			record.put(ProductModelDBHelper.MODEL_NO,
					jsonModel.getString("ModelNo"));
			record.put(ProductModelDBHelper.MODEL_NAME,
					jsonModel.getString("ModelName"));
			data.add(record);

			productModel.setProductId(jsonModel.getLong("ProductID"));
			productModel.setCatName(jsonModel.getString("ProductCategoryName"));
			productModel.setModelNo(jsonModel.getString("ModelNo"));
			productModel.setModelName(jsonModel.getString("ModelName"));
			productModels.add(productModel);
		}

		ProductModelDBHelper.insertNewModels(data);
		result.setData(productModels);
		return result;
	}

	private DataResult parseCreateOpportunity(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {

		DataResult result = new DataResult();
		MethodParams mp = methodParams;

		String[] listIds = (String[]) mp.getTag(Constant.ID_LOCAL);

		ArrayList<String> succeedList = new ArrayList<String>();
		for (int i = 0; i < jsonArray.length(); i++) {

			JSONObject json = (JSONObject) jsonArray.get(i);

			for (int j = 0; j < listIds.length; j++) {
				String id = listIds[j];

				if (json.getString(id).equals("OK")) {
					ProjectDBHelper.syncedDone(id);
					succeedList.add(id);
				}
			}
		}

		result.setData(succeedList);

		return result;
	}

	/**
	 * parse opportunity list by status
	 * 
	 * @param jsonArray
	 * @param methodParams
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseGetOpportunityByStatus(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {

		DataResult result = new DataResult();
		List<Project> projects = new ArrayList<Project>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			Project project = new Project();

			project.setAmount(json.getInt("TotalAmount"));

			project.setCustomerCompanyName(json
					.getString("CustomerCompanyName"));

			project.setName(json.getString("Name"));

			project.setId(json.getString("OpportunityID"));

			project.setDate(json.getString("ExpectedCloseDate"));

			project.setStatus(json.getString("OppStatus"));

			projects.add(project);
		}

		ProjectDBHelper.insertUpdateProjects(projects, true);
		result.setData(projects);
		return result;
	}

	/**
	 * parsing the detail of one Opportunity
	 * 
	 * @param jsonArray
	 * @param methodParams
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseDetailOpportunity(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {

		DataResult result = new DataResult();
		JSONObject json = (JSONObject) jsonArray.get(0);
		Project project = new Project();

		String opportunityID = (String) methodParams.getInputData();

		project.setId(opportunityID);
		project.setAmount(json.getInt("TotalAmount"));
		project.setCustomerCompanyName(json.getString("CustomerCompanyName"));
		project.setName(json.getString("Name"));
		project.setDate(json.getString("ExpectedCloseDate"));
		project.setStatus(json.getString("OppStatus"));

		ProjectDBHelper.insertUpdateProject(project, true);

		result.setData(project);
		return result;
	}

	private DataResult parseSearchOpportunity(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		List<Project> projects = new ArrayList<Project>();
		for (int i = 0; i < jsonArray.length(); i++) {
			Project project = new Project();
			JSONObject json = jsonArray.getJSONObject(i);
			project.setId(json.getString("OpportunityID"));
			project.setAmount(json.getInt("TotalAmount"));
			project.setCustomerCompanyName(json
					.getString("CustomerCompanyName"));
			project.setName(json.getString("Name"));
			String date = json.getString("ExpectedCloseDate");
			Date createDate;
			try {
				createDate = new SimpleDateFormat("yyyy-MM-dd",
						Locale.getDefault()).parse(date);
				project.setDate(createDate.getTime());
			} catch (ParseException e) {
				// Log.e(TAG, e.toString());
			}
			projects.add(project);
		}

		ProjectDBHelper.insertUpdateProjects(projects, true);
		result.setData(projects);
		return result;
	}

	/**
	 * 
	 * @param jsonArray
	 * @param methodParams
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseDeleteOpportunity(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		return result;
	}

	/**
	 * 
	 * @param jsonArray
	 * @param methodParams
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseDeleteClaim(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		return result;
	}

	/**
	 * 
	 * Parse result for create Claim
	 * 
	 * @param jsonarray
	 * @param methodparam
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseCreateClaim(JSONArray jsonArray,
			MethodParams methodparam) throws JSONException {

		DataResult result = new DataResult();

		JSONObject jsonObj = (JSONObject) jsonArray.get(0);

		Claim c = new Claim();
		c.setLocalId(jsonObj.getString("RecordID"));
		c.setId(jsonObj.getLong("ClaimID"));

		// JSONArray jsonArr = jsonObj.getJSONArray("product");
		JSONArray jsonArr = jsonObj.getJSONArray("product");
		for (int i = 0; i < jsonArr.length(); i++) {
			JSONObject json = (JSONObject) jsonArr.get(i);
			// System.out.println("<<<<JSON = " json.ge());
			Product p = new Product();

			p.setProductId(json.getLong("ProductID"));
			p.setQuantity(json.getInt("Quantity"));
			// p.setService_tag(json.getString("SeriveTag"));
			p.setProductClaimId(json.getLong("ProductClaimID"));

			c.getProducts().add(p);
		}

		jsonArr = jsonObj.getJSONArray("image");
		for (int i = 0; i < jsonArr.length(); i++) {

			JSONObject json = (JSONObject) jsonArr.get(i);

			ClaimImage ci = new ClaimImage();

			ci.setClaimImageId(json.getLong("ImageID"));

			ci.setRotateDegree(json.getInt("Degree"));

			ci.setImageLocation(Uri.parse(Utility.myURLencode(json
					.getString("ImagePath"))));

			c.getImages().add(ci);
		}

		ClaimDBHelper.syncFields(c.getLocalId(), c);

		List<Claim> cls = ClaimDBHelper.getNotUpdatedRecords();
		if (cls.size() == 1) {
			DataSync.doSync(new MethodParams(Methods.claimsSync));
		}

		return result;
	}

	/**
	 * 
	 * 
	 * 
	 * @param jsonArray
	 * @param methodParams
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseGetClaimByStatus(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		List<Claim> claims = new ArrayList<Claim>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			Claim claim = new Claim();

			claim.setId(json.getLong("ClaimID"));

			claim.setStatus(json.getString("ClaimStatus"));

			claim.setInvoiceNo(json.getString("InvoiceNo"));

			claim.setCustomerCompanyName(json.getString("CustomerName"));

			claim.setType(json.getString("ClaimType"));

			claim.setDate(json.getString("InvoiceDate"));

			claim.setDistributorId(json.getLong("DistributorID"));

			// if(claim.getId() >0){
			claims.add(claim);
			// }
		}
		SPreferences.setFetched(ClaimDBHelper.TABLE_NAME);

		ClaimDBHelper.insertUpdateClaims(claims, true);

		result.setData(claims);
		System.out.println("From server <<< " + claims.size());
		return result;
	}

	/**
	 * 
	 * 
	 * @param jsonArray
	 * @param methodParams
	 * @return
	 * @throws JSONException
	 */
	private DataResult parseDetailClaim(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();

		Long claimID = (Long) methodParams.getInputData();

		JSONObject json = (JSONObject) jsonArray.get(0);
		Claim claim = new Claim();

		claim.setId(claimID);
		claim.setOpportunityName(json.getString("Name"));
		claim.setCustomerCompanyName(json.getString("CustomerName"));
		claim.setInvoiceNo(json.getString("InvoiceNo"));
		claim.setType(json.getString("ClaimType"));
		claim.setDate(json.getString("InvoiceDate"));
		claim.setDistributorId(json.getLong("DistributorID"));

		JSONArray arrayProducts = json.getJSONArray("ProductDetail");
		List<Product> products = new ArrayList<Product>();
		for (int i = 0; i < arrayProducts.length(); i++) {
			JSONObject jsonProduct = (JSONObject) arrayProducts.get(i);

			String productclaimidS = jsonProduct.getString("ProductClaimID");
			if (!(productclaimidS.length() > 0))
				continue;

			Product product = new Product();
			product.setProductClaimId(Long.parseLong(productclaimidS));

			product.setModelName(jsonProduct.getString("ModelName"));

			product.setModelNo(jsonProduct.getString("ModelNo"));

			product.setService_tag(jsonProduct.getString("SeriveTag"));

			String quantityS = jsonProduct.getString("Quantity");
			if (quantityS.length() > 0)
				product.setQuantity(Integer.parseInt(quantityS));

			String unitpriceS = jsonProduct.getString("UnitPrice");
			if (unitpriceS.length() > 0)
				product.setPrice(Float.parseFloat(unitpriceS));

			products.add(product);
		}

		// /--------------Tam-------------
		JSONArray arrayImage = json.getJSONArray("ImagePath");

		List<ClaimImage> images = new ArrayList<ClaimImage>();

		for (int i = 0; i < arrayImage.length(); i++) {
			JSONObject jsonObject = (JSONObject) arrayImage.get(i);
			try {

				String claimimageidS = jsonObject.getString("ImageID");
				if (!(claimimageidS.length() > 0))
					continue;

				ClaimImage image = new ClaimImage();
				image.setClaimImageId(Long.parseLong(claimimageidS));

				image.setImageLocation(Uri.parse(Utility.myURLencode(jsonObject
						.getString("PhysicalPath"))));

				image.setRotateDegree(jsonObject.getInt("Degree"));

				images.add(image);
			} catch (Exception e) {
				continue;
			}
		}

		claim.setImages(images);

		claim.setProducts(products);

		// store to localDB
		// if(claim.getId() != 0){
		ClaimDBHelper.insertUpdateClaim(claim, true);
		// }

		result.setData(claim);
		return result;
	}

	private DataResult parsePriceBook(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		ArrayList<PriceBook> mData = new ArrayList<PriceBook>();
		String downloadedDatetime = getDateTime();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);

			int pricebookId = json.getInt("PriceBookID");

			boolean isPriceBookExists = PriceBookDBHelper
					.isPriceBookExists(pricebookId);

			if (!isPriceBookExists) {
				PriceBook priceBook = new PriceBook();
				priceBook.setPriceBookID(json.getInt("PriceBookID"));
				priceBook.setPriceBkYear(json.getString("PriceBkYear"));
				priceBook.setPriceBkMonth(json.getInt("PriceBkMonth"));
				priceBook.setPriceBookName(String.valueOf(i));
				priceBook.setSaleCategoryName(json
						.getString("SaleCategoryName"));
				priceBook.setPhysicalPath(json.getString("PhysicalPath"));
				priceBook.setDownloadedDate(downloadedDatetime);
				priceBook.setPhysicalPathLocal("");
				PriceBookDBHelper.createPriceBook(priceBook);
				mData.add(priceBook);
			}
		}
		result.setData(mData);
		return result;
	}

	private String getDateTime() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
		Date date = new Date();
		return dateFormat.format(date);
	}

	private DataResult parsePromotion(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		ArrayList<Promotion> mData = new ArrayList<Promotion>();
		String downloadedDatetime = getDateTime();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);

			int promotionId = json.getInt("AnnouncePromoID");

			boolean isPromotionExists = PromotionDBHelper
					.isPromotionExists(promotionId);
			if (!isPromotionExists) {
				Promotion promotion = new Promotion();
				promotion.setAnnouncePromoID(json.getInt("AnnouncePromoID"));
				promotion.setPromoYear(json.getString("PromoYear"));
				promotion.setPromoMonth(json.getInt("PromoMonth"));
				promotion.setPromotionName(String.valueOf(i));
				promotion.setSaleCategoryName(json
						.getString("SaleCategoryName"));
				promotion.setDownloadedDate(downloadedDatetime);
				promotion.setPhysicalPath(json.getString("PhysicalPath"));
				promotion.setPhysicalPathLocal("");
				PromotionDBHelper.createPromotion(promotion);
				mData.add(promotion);
			}
		}
		result.setData(mData);
		return result;
	}

	private DataResult parseProductImage(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		// Utility.mDataPromotion.clear();
		DataResult result = new DataResult();
		ArrayList<ProductImage> mData = new ArrayList<ProductImage>();
		String downloadedDatetime = getDateTime();
		if (Utility.mDataProductImage != null
				&& Utility.mDataProductImage.size() == 0) {
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = (JSONObject) jsonArray.get(i);
				ProductImage productImage = new ProductImage();
				productImage.setProductInfoID(json.getInt("ProductInfoID"));
				productImage.setProductInfo(json.getString("ProductInfo"));
				productImage.setDescription("");
				productImage.setSaleCategoryName(json
						.getString("SaleCategoryName"));
				productImage.setPhysicalPath(json.getString("PhysicalPath"));
				productImage.setLocalPath("");
				productImage.setDownloadedDate(downloadedDatetime);
				ProductImageDBHelper.createProductImage(productImage);
				mData.add(productImage);
			}
			Utility.mDataProductImage = mData;
		} else if (!Utility.checkGetLastestProduct) {
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = (JSONObject) jsonArray.get(i);
				ProductImage productImage = new ProductImage();
				productImage.setProductInfoID(json.getInt("ProductInfoID"));
				productImage.setProductInfo(json.getString("ProductInfo"));
				productImage.setDescription("");
				productImage.setSaleCategoryName(json
						.getString("SaleCategoryName"));
				productImage.setPhysicalPath(json.getString("PhysicalPath"));
				productImage.setLocalPath("");
				ProductImageDBHelper.createProductImage(productImage);
				mData.add(productImage);
			}
			Utility.mDataProductImage = mData;

		} else {
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject json = (JSONObject) jsonArray.get(i);
				for (int x = 0; x < Utility.mDataProductImage.size(); x++) {
					if (json.getInt("ProductInfoID") == Utility.mDataProductImage
							.get(x).getProductInfoID()) {
						flagCheckProduct = true;
						break;
					}
				}
				if (flagCheckProduct == false) {
					ProductImage productImage = new ProductImage();
					productImage.setProductInfoID(json.getInt("ProductInfoID"));
					productImage.setProductInfo(json.getString("ProductInfo"));
					productImage.setDescription("");
					productImage.setSaleCategoryName(json
							.getString("SaleCategoryName"));
					productImage
							.setPhysicalPath(json.getString("PhysicalPath"));
					productImage.setLocalPath("");
					ProductImageDBHelper.createProductImage(productImage);
					mData.add(productImage);
				}
				flagCheckProduct = false;
			}
			mData = Utility.mDataProductImage;
			Utility.checkGetLastestProduct = false;
		}
		result.setData(mData);
		return result;
	}

	//
	private DataResult parseReward(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		ArrayList<ProgramReward> mData = new ArrayList<ProgramReward>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			// ProgramReward programReward = new ProgramReward();
			int ProgramID = (json.getInt("ProgramID"));
			String ProgramName = (json.getString("ProgramName"));
			String ProgramCode = (json.getString("ProgramCode"));
			String Quarter = (json.getString("Quarter"));
			String Year = (json.getString("Year"));

			JSONArray reward = json.getJSONArray("Reward");

			ArrayList<NewReward> newRewards = new ArrayList<NewReward>();

			for (int x = 0; x < reward.length(); x++) {
				JSONObject jsonObject = (JSONObject) reward.get(x);
				try {
					NewReward rewardData = new NewReward();
					rewardData.setRewardBalanceID(jsonObject
							.getInt("RewardBalanceID"));
					rewardData.setObjectID(jsonObject.getInt("ObjectID"));
					rewardData.setRewardAmount(jsonObject
							.getInt("RewardAmount"));
					rewardData
							.setRewardType(jsonObject.getString("RewardType"));
					rewardData.setProgramID(ProgramID);
					rewardData.setProgramName(ProgramName);
					rewardData.setProgramCode(ProgramCode);
					rewardData.setQuarter(Quarter);
					rewardData.setYear(Year);
					RewardDBHelper.createReward(rewardData);
					// newRewards.add(rewardData);
					// (promotion);
				} catch (Exception e) {
					continue;
				}
			}
		}

		result.setData(mData);
		return result;
	}

	private DataResult parseRewardClaimDetail(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		Utility.mDataClaimDetails.clear();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			NewRewardClaimDetail program = new NewRewardClaimDetail();
			program.setRewardDetailId(i);// (json.getInt("ProgramID"));
			program.setProgramID(json.getInt("ProgramID"));
			program.setModelNo(json.getString("ModelNo"));
			program.setModelName(json.getString("ModelName"));
			program.setClaimID(json.getInt("ClaimID"));
			program.setInvoiceNo(json.getString("InvoiceNo"));
			String invoiceDate = json.getString("InvoiceDate");
			if (invoiceDate != null && invoiceDate.length() > 11) {
				invoiceDate = invoiceDate.substring(0, 10);
			}
			program.setInvoiceDate(invoiceDate);
			program.setDistributorName(json.getString("DistributorName"));
			program.setQuantity(json.getInt("Quantity"));
			program.setProductCategoryID(json.getInt("ProductCategoryID"));
			program.setProductCategoryName(json
					.getString("ProductCategoryName"));
			program.setRewardAmount(json.getInt("RewardAmount"));
			Utility.mDataClaimDetails.add(program);
			RewardClaimDetailDBHelper.createClaimDetail(program);
		}

		// Utility.mDataPriceBook = mData;
		result.setData(Utility.mDataClaimDetails);
		return result;
	}

	private DataResult parseRewardClaim(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		Utility.mDataClaim.clear();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			NewRewardClaim program = new NewRewardClaim();
			program.setIdClaim(i);
			program.setCategoryId(json.getInt("ProductCategoryID"));
			program.setProgramID(json.getInt("ProgramID"));
			program.setProgramName(json.getString("ProgramName"));
			program.setQuarter(json.getString("Quarter"));
			program.setYear(json.getString("Year"));
			program.setProgramCode(json.getString("ProgramCode"));
			program.setProductCategoryName(json
					.getString("ProductCategoryName"));
			program.setTotalRewardAmount(json.getString("TotalRewardAmount"));
			program.setTotalQuantity(json.getString("TotalQuantity"));
			program.setPeriod(json.getString("Quarter")
					+ json.getString("Year"));
			Utility.mDataClaim.add(program);
			RewardClaimDBHelper.createRewardClaim(program);
		}
		// Utility.mDataPriceBook = mData;
		result.setData(Utility.mDataClaim);
		return result;
	}

	private DataResult parseRewardProjectDetail(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		// ArrayList<NewRewardProjectDetail> mData = new
		// ArrayList<NewRewardProjectDetail>();
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			NewRewardProjectDetail program = new NewRewardProjectDetail();
			String invoiceNo = json.getString("InvoiceNo");
			String invoicedate = json.getString("InvoiceDate");
			if (invoiceNo.equals("null")) {
				program.setInvoiceNo("1");
			} else {
				program.setInvoiceNo(invoiceNo);
			}
			if (invoicedate.equals("null")) {
				program.setInvoiceDate("1");
			} else {
				program.setInvoiceDate(invoiceNo);
			}
			program.setOpportunityName(json.getString("OpportunityName"));
			program.setCustomerCompany(json.getString("CustomerCompany"));
			program.setAmount(json.getString("Amount"));
			program.setObjectID(json.getString("ObjectID"));
			program.setRewardType(json.getString("RewardType"));
			RewardProjectDetailDBHelper.createProjectDetail(program);
			Utility.mDataProjectDetails.add(program);
		}
		// Utility.mDataPriceBook = mData;
		result.setData(Utility.mDataProjectDetails);
		return result;
	}

	private DataResult parseRewardProject(JSONArray jsonArray,
			MethodParams methodParams) throws JSONException {
		DataResult result = new DataResult();
		// ArrayList<NewRewardProject> mData = new
		// ArrayList<NewRewardProject>();
		Utility.mDataProject.clear();
		System.out.println(">>JSON LENGTH = " + jsonArray.length());
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject json = (JSONObject) jsonArray.get(i);
			NewRewardProject program = new NewRewardProject();
			program.setProgramID(json.getString("ProgramID"));
			program.setProgramName(json.getString("ProgramName"));
			program.setQuarter(json.getString("Quarter"));
			program.setYear(json.getString("Year"));
			program.setProgramCode(json.getString("ProgramCode"));
			program.setTotalRewardAmount(json.getString("TotalRewardAmount"));
			program.setRewardType(json.getString("RewardType"));
			program.setName(json.getString("Name"));
			program.setObjectID(json.getString("ObjectID"));
			program.setTotalAmount(json.getString("TotalAmount"));
			program.setPeriod(json.getString("Quarter")
					+ json.getString("Year"));
			RewardProjectDBHelper.createRewardProject(program);
			Utility.mDataProject.add(program);
		}
		// Utility.mDataPriceBook = mData;
		result.setData(Utility.mDataProject);
		return result;
	}

}